<?php

namespace app\api\controller;

use app\common\controller\Common;
use GatewayClient\Gateway;
use think\facade\Db;
use think\Request;

/**
 * 对话平台 api类
 * Class Chats
 * @package app\api\controller
 */
class Chats extends Common
{
    /**
     * 获取当前客服的对话游客列表
     */
    public function getchats(Request $r)
    {
        if ($r->isAjax()) {
            $dialogue = Db::name('im_dialogue')->alias('d')
                ->field('d.vsid,d.new_cont,v.avatar,v.nick,d.unread_count,v.state')
                ->join('we_im_visitors v','v.id=d.vsid')
                ->where(['d.cuid' => $this->custs['id'], 'd.isshow' => 1 , 'v.is_act' =>1])
                ->limit(30)->order('d.add_time desc')->select();
            return json(['code' => 200, 'data' => $dialogue]);
        }
    }

    /**
     *获取当前客服的黑名单
     */
    public function getBlacklist(Request $r)
    {
        if ($r->isAjax()) {
            $dialogue = Db::name('im_blacklist')->alias('b')
                ->field('b.id,b.vsid,v.avatar,v.nick')
                ->join('we_im_visitors v','v.id=b.vsid')
                ->where('b.cuid', $this->custs['id'])
                ->limit(30)->order('b.add_time desc')->select();
            return json(['code' => 200, 'data' => $dialogue]);
        }
    }

    /**
     * 获取快捷回复分组列表
     */
    public function getGroupList(Request $r)
    {
        if ($r->isAjax()) {
            $fastreply_group = Db::name('im_fastreply_group')
                ->where('cuid', $this->custs['id'])
                ->order('add_time desc')->select();
            return json(['code' => 200, 'data' => $fastreply_group]);
        }
    }

    /**
     * 根据分组id获取回复列表
     */
    public function getReplyList(Request $r)
    {
        if ($r->isAjax()) {
            $group_id = $r->post('group_id', 0, 'imDataFilter');
            $fastreply = Db::name('im_fastreply')
                ->field('id,title,content')
                ->where(['group_id' => $group_id, 'cuid' => $this->custs['id']])
                ->order('add_time desc')->select();
            return json(['code' => 200, 'data' => $fastreply]);
        }
    }

    /**
     * 删除分组以及分组下所有回复
     */
    public function delGroup(Request $r)
    {
        if ($r->isAjax()) {
            $group_id = $r->post('group_id', 0, 'imDataFilter');
            $where = ['group_id' => $group_id, 'cuid' => $this->custs['id']];

            $fastreply = Db::name('im_fastreply')->where($where)->count();
            if ($fastreply) {
                Db::name('im_fastreply')->where($where)->delete();
            }

            Db::name('im_fastreply_group')->delete($group_id);
            return json(['code' => 200, 'data' => []]);
        }
    }

    /**
     * 删除快捷回复
     */
    public function delReply(Request $r)
    {
        if ($r->isAjax()) {
            $reply_id = $r->post('reply_id', 0, 'imDataFilter');
            $where = ['id' => $reply_id, 'cuid' => $this->custs['id']];
            Db::name('im_fastreply')->where($where)->delete();
            return json(['code' => 200, 'data' => []]);
        }
    }

    /**
     * 游客端 加载历史消息
     */
    public function loadRecordLists(Request $r)
    {
        if ($r->isAjax()) {
            $post = $r->post();
            $record = Db::name('im_record')
                ->where("send = {$post['fromid']} AND receive = {$post['toid']}")
                ->whereOr("send = {$post['toid']} AND receive = {$post['fromid']}")
                ->whereOr("source_cuid = {$post['fromid']} AND receive = {$post['toid']}")
                ->whereOr("send = {$post['toid']} AND source_cuid = {$post['fromid']}")
                ->page($post['page'],10)->order('send_time desc')->select();
            $data = array_reverse($record->toArray());
            if (!empty($data)) {
                return json([
                    'code' => 200,
                    'data' => $data
                ]);
            } else {
                return json([
                    'code' => 300,
                    'data' => []
                ]);
            }
        }
    }

    /**
     * 获取当前客户端ip及地址
     */
    public function getIpinfo(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $vsid = $r->post('vsid', false);
            $ip = Db::name('im_visitors')
                ->where('id', $vsid)->value('ip');
            if (!$ip) {
                $ip = $r->ip();
            }else{
                $ip = explode(':',$ip)[0];
            }
            $info = Db::name('im_visitors_info')
                ->field('id,city')->where('vsid', $vsid)->find();
            if (empty($info['city'])) {
                $city = "";
                $data = curl_get('https://www.ip138.com/iplookup.asp', $get_data = [
                    'ip'     => $ip,
                    'action' => 2
                ]);
                preg_match_all("/\{\"ASN归属地\":\"(.*?)\",/", gbk2utf8($data), $match);
                if (!empty($match[1][0])) {
                    $city = $match[1][0];
                }
                Db::name('im_visitors_info')->save(['id' => $info['id'], 'city' => $city]);
            } else {
                $city = $info['city'];
            }
            if (!empty($city)) {
                return json([
                    'code' => 200,
                    'data' => $city
                ]);
            }
        }
    }

    /**
     * 获取游客全部信息
     */
    public function getVisitors(Request $r)
    {
        if ($r->isAjax() && $r->isAjax()) {
            $vsid = $r->post('vsid', 0, 'intval');
            $visitors = Db::name('im_visitors')
                ->field('vi.id,v.ip,v.avatar,v.nick,vi.source,vi.city,v.state,v.last_time,vi.views,vi.equi,vi.name,vi.phone,vi.note')
                ->alias('v')->join('we_im_visitors_info vi','vi.vsid=v.id')
                ->where(['v.id' => $vsid, 'cuid' => $this->main_id])->find();
            if (!empty($visitors)) {
                $visitors['last_time'] = date('Y年m月d日 H:i', $visitors['last_time']);
                $visitors['views'] = $visitors['views'] . '次';
                if ($visitors['state'] == 1) {
                    $visitors['state'] = '在线';
                } else {
                    $visitors['state'] = '离线';
                }
                $visitors['ip'] = $visitors['ip'] ? explode(':',$visitors['ip'])[0] :$visitors['ip'];
                return json([
                    'code' => 200,
                    'data' => $visitors
                ]);
            } else {
                return json([
                    'code' => 300,
                    'data' => []
                ]);
            }
        }
    }

    /**
     * 查看和某个游客的历史记录
     */
    public function getOneHistoryLists(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data   = $r->post();
            $fromid = $data['cuid']??0;
            $toid   = $data['vsid']??0;
            $type   = $data['type']??'7day';

            $record = Db::name('im_record')
                ->field('send,send_avatar,receive,receive_avatar,utype,content')
                ->whereMonth('send_time')
                ->where("send = {$fromid} AND receive = {$toid} OR send = {$toid} OR receive = {$fromid}")
                ->order('send_time desc')
                ->select();

            if (!$record->isEmpty()) {
                $record = array_reverse($record->toArray());
                return json(['code' => 200, 'data' => $record]);
            } else {
                return json(['code' => 300, 'msg' => '无数据']);
            }
        }
    }

    /**
     * 获取当前主客服下的全部客服
     */
    public function getCustomerLists(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $customer = Db::name('im_customer')
                ->field('id,avatar,nick,state')
                ->where("pid=".$this->main_id." or id=".$this->main_id)
                ->order('login_time desc')->select();

            // 这里也没有判断客服是否在线
            // 判断在线状态
            Gateway::$registerAddress = config('im.Register_ip') . ':' . config('im.Register_port');

            if (!$customer->isEmpty()) {
                $customer = $customer->toArray();
                $customerLists = [] ;
                foreach ($customer as $key=>$item) {
                    if ($item['id'] == $this->custs['id']) {
                        unset($customer[$key]);
                        continue;
                    }
                    //$customer[$key]['online_status'] = Gateway::isUidOnline($item['id']) ;
                    $item['online_status'] = Gateway::isUidOnline($item['id']) ;
                    $item['online_status'] == 1
                        ? array_unshift($customerLists,$item)
                        : array_push($customerLists,$item);
                }
                return json(['code' => 200, 'data' => $customerLists]);
            } else {
                return json(['code' => 300, 'msg' => '无数据']);
            }
        }
    }
}
